package util;

import com.google.common.collect.Maps;
import enums.PlatformTypeEnum;
import exception.AncException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 终端类型判断工具
 * Create on 2019-09-03 14:42
 *
 * @author tianbl
 */
@Slf4j
public class UserAgentUtil {

    /**
     * 获取终端类型工具类
     *
     * @param request 请求
     * @return 平台类型
     */
    public static PlatformTypeEnum getCurrentPlatformType(HttpServletRequest request) {
        String useragent = request.getHeader("user-agent");
        if (StringUtils.isNotBlank(useragent)) {
            useragent = useragent.toLowerCase();
            if (useragent.contains("micromessenger")) {
                return PlatformTypeEnum.WECHAT;
            }
            if (useragent.contains("alipay")) {
                return PlatformTypeEnum.ALIPAY;
            }
            if (useragent.contains("dajia/")) {
                return PlatformTypeEnum.APP;
            }
            if (useragent.contains("odian")) {
                return PlatformTypeEnum.APP;
            }
        }
        return PlatformTypeEnum.WEBBROWSER;
    }

    /**
     * 获取app中的参数
     *
     * @param request 请求
     * @return 参数
     */
    public static Map<String,String> getAppConfig(HttpServletRequest request) {
        Map<String, String> parseMap = Maps.newHashMap();
        String useragent = request.getHeader("user-agent");
        if (null != useragent) {
            try {
                if (useragent.indexOf("dajia/") > -1) {
                    int start = useragent.indexOf("dajia/");
                    start += 6;
                    String jsonString = useragent.substring(start);
                    parseMap = JsonUtil.readValue2Map(jsonString, String.class, String.class);
                }
            } catch (AncException e) {
                log.error("解析uesrgent失败:" + useragent, e);
            }
        }
        return parseMap;
    }
}
